package com.education.teach.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.dn.res.wideget.DnToolbar;
import com.education.teach.R;
import com.education.teach.di.component.DaggerCoursewareDeatilComponent;
import com.education.teach.di.module.CoursewareDeatilModule;
import com.education.teach.mvp.contract.CoursewareDeatilContract;
import com.education.teach.mvp.model.service.ApiService;
import com.education.teach.mvp.presenter.CoursewareDeatilPresenter;
import com.education.teach.utils.FileUtils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.utils.ArmsUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileOutputStream;

import javax.inject.Inject;

import butterknife.BindView;
import dn.easy.common.commonutils.LogUtils;
import dn.easy.common.commonutils.StringUtils;
import dn.easy.common.commonwidget.AVLoadingDialog;
import dn.easy.common.constant.Contans;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.ResponseBody;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class CoursewareDeatilActivity extends BaseActivity<CoursewareDeatilPresenter> implements CoursewareDeatilContract.View {

    @BindView(R.id.toolbar)
    DnToolbar mToolbar;
    @BindView(R.id.tv_work_title)
    TextView mTvWorkTitle;
    @BindView(R.id.tv_work_user)
    TextView mTvWorkUser;
    @BindView(R.id.tv_work_date)
    TextView mTvWorkDate;
    @BindView(R.id.tv_work_realurl)
    TextView mTvWorkRealurl;
    @BindView(R.id.desp)
    TextView mDesp;
    @BindView(R.id.btn_download)
    Button mBtnDownload;

    @Inject
    IRepositoryManager mIRepositoryManager;
    @Inject
    RxErrorHandler mRxErrorHandler;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerCoursewareDeatilComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .coursewareDeatilModule(new CoursewareDeatilModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_courseware_deatil; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mToolbar.setMainTitle("作品详情");
        mToolbar.setToolbarLeftBackImageRes(R.mipmap.top_back);
        mToolbar.setOnLeftTitleClickListener(view -> finish());

        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        String desp = intent.getStringExtra("desp");
        String fileType = intent.getStringExtra("fileType");
        String createName = intent.getStringExtra("createName");
        String realUrl = intent.getStringExtra("realUrl");
        String fileurl = intent.getStringExtra("url");
        String date = intent.getStringExtra("date");
//

        if (StringUtils.isEmpty(desp)) {
//            mDesp.setVisibility(View.GONE);
        } else
            mDesp.setText(desp);

        mTvWorkTitle.setText(title);
        mTvWorkUser.setText("作者:" + createName);
        mTvWorkDate.setText(date);
        mTvWorkRealurl.setText(realUrl);
        ;
        LogUtils.logi(Contans.BASE_DOWNLOAD_URL + fileurl);
        mBtnDownload.setOnClickListener(v -> {
            RxPermissions rxPermissions = new RxPermissions(this);// 获取写内存的权限
            rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(granted -> {
                        if (granted) {
                            mIRepositoryManager
                                    .obtainRetrofitService(ApiService.class)
                                    .loadFile(Contans.BASE_DOWNLOAD_URL + fileurl)
                                    .flatMap(responseBody -> {
                                        FileUtils.savePdfFile(Contans.PDFLOCATION + "/" + fileurl + "_" + realUrl, responseBody.bytes());
                                        return Observable.just("下载成功");
                                    })
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .doOnSubscribe(disposable -> showLoading())
                                    .doFinally(() -> hideLoading())
                                    .subscribe(new ErrorHandleSubscriber<String>(mRxErrorHandler) {
                                        @Override
                                        public void onNext(String string) {
                                            showMessage("下载成功！");
                                        }
                                    });

                        }
                    });


        });
    }

    @Override
    public void showLoading() {
        AVLoadingDialog.showDialogForLoading(this);
    }

    @Override
    public void hideLoading() {
        AVLoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

}
